package com.sq.universe.base.interceptor;

import com.sq.universe.base.entity.BusinessException;
import com.sq.universe.base.entity.RespEntity;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理自定义的业务异常
     * @param req
     * @param exception
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public RespEntity bizExceptionHandler(HttpServletRequest req, HttpServletResponse response, Exception exception) throws IOException {
        exception.printStackTrace();
        log.error("发生业务异常！原因是：{}",exception.getMessage());
        if(exception instanceof BusinessException){
            BusinessException businessException = (BusinessException)exception;
            return new RespEntity(businessException.getMessage(), Integer.valueOf(businessException.getErrorCode()));
        }
        if(exception instanceof UnauthenticatedException){
            UnauthenticatedException businessException = (UnauthenticatedException)exception;

            return new RespEntity(businessException.getMessage(),401);
        }
        return RespEntity.error("未知异常请联系,系统管理员");
    }

}
